package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;

/**
 * Phaser可以通过register来增加同步线程数
 * Created by gavin on 15-9-1.
 */
public class PhaserTest {
    public static void main(String[] args)
    {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Phaser phaser = new Phaser(5);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new PhaserTongbu(phaser));
            //phaser.register();
        }
    }
}

class PhaserTongbu implements Runnable{
    private Phaser phaser;

    public void run() {

        try {
            Thread.sleep(new Random().nextInt(3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" 1");
        phaser.arriveAndAwaitAdvance();

        try {
            Thread.sleep(new Random().nextInt(3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" 2");
        phaser.arriveAndAwaitAdvance();

        try {
            Thread.sleep(new Random().nextInt(3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" 3");
        phaser.arriveAndAwaitAdvance();
    }

    public PhaserTongbu(Phaser phaser) {
        this.phaser = phaser;
    }
}
